package com.neuedu.boot.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.boot.config.CommonResult;
import com.neuedu.boot.entity.User;
import com.neuedu.boot.service.IUserService;
import com.neuedu.boot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    IUserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    ObjectMapper objectMapper;

    @RequestMapping("/login")
    CommonResult login(User user) throws JsonProcessingException {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password",user.getPassword());

//        queryWrapper.
        User one = userService.getOne(queryWrapper);
        if(one!= null){



            //更新最后一次登录时间
            one.setLastlogin(LocalDateTime.now());
            userService.updateById(one);

            User redisUser = new User();
            redisUser.setUserId(one.getUserId());
            redisUser.setUsername(one.getUsername());
            redisUser.setRealname(one.getRealname());
            redisUser.setLastlogin(one.getLastlogin());

            //将User对象转换成JSON存到redis中
            String json = objectMapper.writeValueAsString(redisUser);

            //将Token放到缓存中
            String key = "LOGIN_INFO_"+user.getUsername();
            redisService.set(key, json ,1800);



            //使用用户身份生成jwt token ，发送个浏览器
            String secret = "abcdef";
            long longLastlogin = one.getLastlogin().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
            String token = JWT.create().
                    withClaim("userId", one.getUserId()).  //设置登录用户id
                    withClaim("username", one.getUsername()).  //设置登录的用户名
                    withClaim("lastlogin", longLastlogin).  //设置最后一次登录时间
                    sign(Algorithm.HMAC256(secret));

            return CommonResult.success(token);
        }else{
            return CommonResult.failed("用户名或密码不正确");
        }

    }


}
